<template>
  <c-loading :loading="loading">
    <c-form>
      <view class="container top-line">
        <c-cell-box label="姓名" type="text" name="consignee" :maxlength="20" v-model="state.consignee"></c-cell-box>
        <c-cell-box label="手机号" type="number" name="consigneePhone" :maxlength="11" v-model="state.consigneePhone"></c-cell-box>
        <c-cell-box label="所在地区" type="cascader" name="province" v-model="state.region" range-key="name" range-value="name" :range="regions"></c-cell-box>
        <c-cell-box label="详细地址" name="address">
          <template #break="{ clearMsg }">
            <view class="textarea">
              <textarea :rows="5" placeholder="请输入详细地址" @input="clearMsg" :maxlength="100" v-model="state.address"></textarea>
            </view>
          </template>
        </c-cell-box>
        <c-cell-box label="设为默认" type="switch" v-model="state.isDefault"></c-cell-box>
        <view class="fixed-footer shadow">
          <c-button type="primary" @tap="onSubmit">保存</c-button>
        </view>
        <view class="end"></view>
      </view>
    </c-form>
  </c-loading>
</template>
<script setup>
import { CButton, CLoading, CCellBox, CForm } from '@/components';
import { useLoading } from '@/hooks';
import { View, Textarea } from '@tarojs/components';
import { useRouter } from '@/hooks';
import api from '@/api';
import { addressResolve } from '@/hooks/address';
import { reactive, ref } from 'vue';
import { getClipboardData, setClipboardData, useDidShow } from '@tarojs/taro';
import toast from '@/utils/toast';

const state = reactive({
  consignee: '',
  consigneePhone: '',
  region: [],
  address: '',
  isDefault: false
});

const regions = ref([]);
const router = useRouter();

const onResolve = () => {
  getClipboardData({
    success(data) {
      if (data.data) {
        const res = addressResolve(data.data, regions.value);
        if (res) {
          toast.confirm('检查到剪贴板有地址信息是否使用？').then(() => {
            const { address, fullName, mobile, region } = res;
            state.consignee = fullName;
            state.consigneePhone = mobile;
            state.address = address;
            state.region = region;
          });
        }
      }
    }
  });
};
const { loading } = useLoading(async (options, data) => {
  regions.value = await api.bus.regionGetTree();
  Object.assign(state, data ?? {});
  onResolve();
});

useDidShow(() => {
  if (regions.value.length) onResolve();
});

const onSubmit = () => {
  return api.user
    .userAddressSave({ ...state })
    .success('保存成功')
    .then(r => {
      router.back();
    });
};
</script>
<style lang="scss"></style>
